﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/**
 * 这里处理资源的加载逻辑
 * 
 * 
 * 
 */

public class LoadLogic
{

	class LoadPath
	{
		public static string assetBundlePath = Application.streamingAssetsPath + "/assetbundles";
	}

	private static LoadLogic instance = new LoadLogic();
	public static LoadLogic getInstance()
	{
		return instance;
	}
	//参数是assetbundle + "/" + perfab

	private Dictionary<string, List<GameObject>> loadCatch = new Dictionary<string, List<GameObject>>();
	private Dictionary<string, AssetBundle> assetbundleCatch = new Dictionary<string, AssetBundle>();

	public IEnumerable load(string resPath, Action<GameObject> callback)
	{
		GameObject result = null;
		if (this.loadCatch.ContainsKey(resPath))
		{
			if (loadCatch[resPath].Count > 0)
			{
				result = loadCatch[resPath][0];
				result.SetActive(true);
				loadCatch[resPath].Remove(result);
				callback(result);
				yield break;
			}
		}
		string[] tempStr = resPath.Split('/');
		if (tempStr.Length != 2)
		{
			Debug.Log("variable error LoadLogic load: " + resPath);
			yield break;
		}
		string assetbundleName = tempStr[0];
		string prefabName = tempStr[1];
		if (assetbundleCatch.ContainsKey(assetbundleName))
		{
			GameObject obj = GameObject.Instantiate((GameObject)this.assetbundleCatch[assetbundleName].LoadAsset(prefabName));
			obj.SetActive(true);
			callback(obj);
			yield break;
		}
		else
		{
			AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(LoadPath.assetBundlePath + "/" + assetbundleName);
			yield return request;
			AssetBundle ab = request.assetBundle;
			this.assetbundleCatch.Add(assetbundleName, ab);
			GameObject obj = GameObject.Instantiate((GameObject)ab.LoadAsset(prefabName));
			obj.SetActive(true);
			callback(obj);
			yield break;
		}
	}

	private IEnumerable loadAssetBundle(String assetbundleName ) {
		AssetBundleCreateRequest request = AssetBundle.LoadFromFileAsync(LoadPath.assetBundlePath + "/" + assetbundleName);
		yield return request;
		AssetBundle manifestAB = request.assetBundle;
		AssetBundleManifest manifest = manifestAB.LoadAsset<AssetBundleManifest>("AssetBundlemanifest");
		string[] ependencies = manifest.GetAllDependencies(assetbundleName);
		foreach (var item in ependencies)
		{
			AssetBundleCreateRequest tempRequest = AssetBundle.LoadFromFileAsync(LoadPath.assetBundlePath + "/" + assetbundleName);
			yield return tempRequest;
			AssetBundle tempManifestAB = tempRequest.assetBundle;
		}
	}

}
